package cn.itsource.org.controller;

import cn.itsource.basic.annotation.Repeat;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.pojo.domain.User;
import cn.itsource.org.query.UserQuery;
import cn.itsource.org.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理", description = "用户操作接口")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 验证手机号
     */
    @GetMapping("/checkphone/{phone}")
    @ApiOperation(value = "验证手机号")
    public AjaxResult checkphone(@PathVariable("phone") String phone) {

        //验证手机号
        return userService.checkPhone(phone);

    }
    /**
     * 发送验证码
     * localhost/send?phone=1777777   @RequestParam("phone") String phone
     */
    @GetMapping("/sendmobilecode")
    @ApiOperation(value = "发送验证码")
    @Repeat(5) //什么都不写取默认值1分钟 @Repeat(value=5) 和@Repeat(5) 都是5分钟
    public AjaxResult sendMobileCode(@RequestParam("phone") String phone, HttpServletRequest request) {

        //验证手机号
        return userService.sendMobileCode(phone,request);
    }


    /**
     * 注册
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册账号")
    public AjaxResult registerUser(@RequestBody @Validated(User.PhoneRegister.class) User user) {

        //注册账号
        return userService.registerUser(user);
    }


    /**
     * 查询所有
     */
    @GetMapping
    @ApiOperation(value = "查询所有用户信息", notes = "查询所有用户信息，get请求")
    public List<User> findAll() {
        return userService.findAll();
    }

    /**
     * 查询所有
     */
    @PostMapping("/findPage")
    @ApiOperation(value = "查询部门分页数据", notes = "查询数据")
    public PageList<User> findPage(@RequestBody UserQuery userQuery) {
        //查询分页数据
        return userService.findPage(userQuery);
    }

    /**
     * 新增或修改的操作
     * 根据id来区分新增和修改
     * 怎么区分请求使用的请求方式  这里是post
     */
    @PostMapping
    public AjaxResult saveOrUpdate(@RequestBody @Valid User user) {

        //没有id就是新增
        userService.saveOrUpdate(user);

        //返回成功对象
        return AjaxResult.createSuccess();
    }

    /**
     * 删除操作
     */
    @DeleteMapping("{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {

        userService.delete(id);
        //返回成功对象
        return AjaxResult.createSuccess();

    }

    /**
     * 批量删除操作
     */
    @PostMapping("/batchDelete")
    public AjaxResult delete(@RequestBody UserQuery userQuery) {

        //批量删除操作
        userService.batchDelete(userQuery.getIds());
        //返回成功对象
        return AjaxResult.createSuccess();
    }


}
